package com.zuipin.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zuipin.entity.DeliveryAddress;
import com.zuipin.framework.emuns.ErrorCode;
import com.zuipin.framework.exception.CustomException;
import com.zuipin.framework.result.Result;
import com.zuipin.mapper.DeliveryAddressMapper;
import com.zuipin.service.IDeliveryAddressService;
import com.zuipin.util.ConstantsUtil;
import com.zuipin.util.DateUtils;
import com.zuipin.util.Pagination;

/**
 * @ClassName: DeliveryAddressServiceImpl
 * @author wuyicheng
 * @time 2017年3月27日下午4:01:46
 */
@Service
public class DeliveryAddressServiceImpl implements IDeliveryAddressService {
	@Resource
	private DeliveryAddressMapper	deliveryAddressMapper;
	
	private static Logger			log	= LoggerFactory.getLogger(DeliveryAddressServiceImpl.class);
	
	/**
	 * @Title: findById
	 * @author: wuyicheng
	 * @date: 2017年3月27日下午5:14:05
	 * @param id
	 * @return
	 * @throws
	 */
	@Override
	public DeliveryAddress findById(Long id) {
		return deliveryAddressMapper.findById(id);
	}
	
	/**
	 * 新增收货地址
	 * 
	 * @Title: insert
	 * @author: wuyicheng
	 * @date: 2017年3月27日下午5:14:05
	 * @param deliveryAddress
	 * @throws
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public void insert(DeliveryAddress deliveryAddress) {
		// 插入之前先判断是否存在默认地址
		DeliveryAddress defaultAddress = findDefault(deliveryAddress.getMemberId(),
				deliveryAddress.getSysId());
		//如果默认地址不存在，新增胡地址就是默认地址
		if (defaultAddress == null) {
			
			deliveryAddress.setIsDefault(DeliveryAddress.IS_DEFUALT_YES_1);
			
		} else {
			// 如果默认地址存在，且当前保存胡地址是默认地址，则删除原来默认
			deleteAllDefultFlag(deliveryAddress);
		}
		deliveryAddress.setCreateTime(DateUtils.getCurrentDateTime());
		deliveryAddress.setUpdateTime(DateUtils.getCurrentDateTime());
		deliveryAddress.setDelFlag(ConstantsUtil.DEL_FLAG_NO_0);
		deliveryAddressMapper.insert(deliveryAddress);
	}
	
	/** 
	 *
	 * @Title: isExistDefault 
	 * @author: wuyicheng
	 * @date: 2017年5月12日下午2:24:19 
	 * @param deliveryAddress
	 * @return: void
	 * @throws 
	 */
	private boolean isExistDefault(DeliveryAddress deliveryAddress) {
		// TODO Auto-generated method stub
		return false;
	}
	
	/**
	 * 更新默认地址为非默认
	 *
	 * @Title: deleteAllDefultFlag 
	 * @author: wuyicheng
	 * @date: 2017年4月24日上午1:44:46 
	 * @param deliveryAddress
	 * @return: void
	 * @throws
	 */
	public void deleteAllDefultFlag(DeliveryAddress deliveryAddress) {
		if (DeliveryAddress.IS_DEFUALT_YES_1 == deliveryAddress.getIsDefault()) {
			deliveryAddressMapper.deleteAllDefultFlag(deliveryAddress);
		}
	}
	
	/**
	 * @throws CustomException 
	 * @Title: update
	 * @author: wuyicheng
	 * @date: 2017年3月27日下午5:14:05
	 * @param deliveryAddress
	 * @throws
	 */
	
	public void update(DeliveryAddress deliveryAddress) {
		deliveryAddress.setUpdateTime(DateUtils.getCurrentDateTime());
		deliveryAddressMapper.update(deliveryAddress);
	}
	
	/**
	 * 
	 *
	 * @Title: updateDeliveryAddress 
	 * @author: wuyicheng
	 * @date: 2017年5月12日下午4:10:39 
	 * @param deliveryAddress
	 * @throws CustomException
	 * @throws
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public void updateDeliveryAddress(DeliveryAddress deliveryAddress) throws CustomException {
		//默认地址排第一位
		List<DeliveryAddress> list = findListByMemberIdAndSysId(deliveryAddress, null);
		
		//如果只有一个地址，且是默认地址，则直接更新地址
		if (DeliveryAddress.IS_DEFUALT_YES_1 == deliveryAddress.getIsDefault() && list != null
				&& list.size() == 1) {
			
			// 直接更新
			
		} else if (list != null && list.size() >= 2) {
			
			// 如果总的地址数>=2才能修改默认标志
			// 修改原来的默认地址为非默认
			if (DeliveryAddress.IS_DEFUALT_YES_1 == deliveryAddress.getIsDefault()) {
				deliveryAddressMapper.deleteAllDefultFlag(deliveryAddress);
			} else {
				DeliveryAddress defaultAddress = list.get(0);
				if (defaultAddress.getId().longValue() == deliveryAddress.getId().longValue()) {
					if (DeliveryAddress.IS_DEFUALT_YES_1 == defaultAddress.getIsDefault()) {
						//获取第二个地址修改成默认
						defaultAddress = list.get(1);
					}
					defaultAddress.setIsDefault(DeliveryAddress.IS_DEFUALT_YES_1);
					update(defaultAddress);
				} else {
					//不操作
				}
				
			}
			
		} else {
			
			//只有一个地址，不能修改成非默认
			throw new CustomException(ErrorCode.ILLEGAL_PARAM.getCode(),
					"There is only one address, which cannot be changed to non-default");
		}
		
		update(deliveryAddress);
	}
	
	/** 
	 *
	 * @Title: findList 
	 * @author: wuyicheng
	 * @date: 2017年4月23日下午2:02:29 
	 * @param memberId
	 * @param sysId
	 * @param page
	 * @return
	 * @throws 
	 */
	@Override
	public List<DeliveryAddress> findList(Long memberId, Long sysId, Pagination page) {
		DeliveryAddress deliveryAddress = new DeliveryAddress();
		deliveryAddress.setMemberId(memberId);
		deliveryAddress.setSysId(sysId);
		return deliveryAddressMapper.findListByMemberIdAndSysId(deliveryAddress, page);
	}
	
	/** 
	 *
	 * @Title: findDefault 
	 * @author: wuyicheng
	 * @date: 2017年4月23日下午2:02:29 
	 * @param memberId
	 * @param sysId
	 * @return
	 * @throws 
	 */
	@Override
	public DeliveryAddress findDefault(Long memberId, Long sysId) {
		Map<String, Object> map = new HashMap<>();
		map.put("memberId", memberId);
		map.put("sysId", sysId);
		return deliveryAddressMapper.findDefault(map);
	}
	
	/**
	 * @throws CustomException  
	 *
	 * @Title: deleteAddress 
	 * @author: wuyicheng
	 * @date: 2017年4月25日上午2:37:32 
	 * @param memberId
	 * @param sysId
	 * @param deliveryAddressId
	 * @param result
	 * @return
	 * @throws 
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public Result<Map<String, Object>> deleteAddress(Long memberId, Long sysId,
			Long deliveryAddressId, Result<Map<String, Object>> result) throws CustomException {
		if (deliveryAddressId != null) {
			DeliveryAddress deliveryAddress = findById(deliveryAddressId);
			if (deliveryAddress != null) {
				deliveryAddress.setDelFlag(ConstantsUtil.DEL_FLAG_YES_1);
				Short isDefault = deliveryAddress.getIsDefault();
				deliveryAddress.setIsDefault(DeliveryAddress.IS_DEFUALT_NO_0);
				update(deliveryAddress);
				
				//如果被删除的是默认地址则将列表的第一个地址设为默认，否则不重新设置默认地址 
				if (isDefault.equals(DeliveryAddress.IS_DEFUALT_YES_1)) {
					List<DeliveryAddress> list = findList(memberId, sysId, null);
					if (list != null && list.size() > 0) {
						deliveryAddress = list.get(0);
						deliveryAddress.setIsDefault(DeliveryAddress.IS_DEFUALT_YES_1);
						update(deliveryAddress);
					}
				}
				
				result.setErrorCode(ErrorCode.SUCCESS);
				result.setData(null);
			} else {
				result.setErrorCode(ErrorCode.NOT_FIND);
				result.setData(null);
			}
		} else {
			result.setErrorCode(ErrorCode.NULL_POINT);
			result.setData(null);
		}
		return result;
	}
	
	/** 
	 *
	 * @Title: findListByMemberIdAndSysId 
	 * @author: wuyicheng
	 * @date: 2017年4月25日上午9:37:38 
	 * @param deliveryAddress
	 * @param page
	 * @return
	 * @throws 
	 */
	@Override
	public List<DeliveryAddress> findListByMemberIdAndSysId(DeliveryAddress deliveryAddress,
			Pagination page) {
		return deliveryAddressMapper.findListByMemberIdAndSysId(deliveryAddress, page);
	}
	
}
